#include "sendnotificationdialog.h"
#include <QDebug>

extern "C" {
#include "notification.h"
#include "part1.h"
}

// Constructor
SendNotificationDialog::SendNotificationDialog(const QString& senderUsername, QWidget *parent)
    : QDialog(parent), ui(new Ui::sendnotificationdialog), m_senderUsername(senderUsername)
{
    ui->setupUi(this);
    setWindowTitle("发送通知");

    // Initialize UI elements
    ui->ReceiverEdit->setPlaceholderText("接收者用户名");

    // Initially hide receiver field for system announcements
    ui->ReceiverEdit->setVisible(false);

    // Connect signal for type change
    connect(ui->TypeComboBox, QOverload<int>::of(&QComboBox::currentIndexChanged),
            this, &SendNotificationDialog::on_TypeComboBox_currentIndexChanged);

    // Set initial state based on selected type
    on_TypeComboBox_currentIndexChanged(ui->TypeComboBox->currentIndex());
}

// Destructor
SendNotificationDialog::~SendNotificationDialog()
{
    delete ui;
}

// Handle send button click
void SendNotificationDialog::on_SendBtn_clicked()
{
    QString title = ui->notificationTitleEdit->text().trimmed();
    QString content = ui->notificationContentEdit->toPlainText().trimmed();

    // Validate input
    if (content.isEmpty()) {
        QMessageBox::warning(this, "错误", "通知内容不能为空");
        return;
    }

    bool success = false;

    // Check notification type
    if (ui->TypeComboBox->currentIndex() == 0) { // System announcement
        if (title.isEmpty()) {
            QMessageBox::warning(this, "错误", "系统公告需要标题");
            return;
        }

        // Initialize users list from file for broadcasting
        init_users_for_notification("users.txt");

        // Send system announcement
        success = sendSystemAnnouncement(title, content);

        // Clean up
        cleanup_notification_system();
    }
    else { // Personal notification
        QString receiver = ui->ReceiverEdit->text().trimmed();

        if (receiver.isEmpty()) {
            QMessageBox::warning(this, "错误", "请输入接收者用户名");
            return;
        }

        // Verify username exists
        if (!isValidUsername(receiver)) {
            QMessageBox::warning(this, "错误", "用户名不存在");
            return;
        }

        // Send personal notification
        success = sendPersonalNotification(receiver, content);
    }

    // Show result
    if (success) {
        QMessageBox::information(this, "成功", "通知发送成功");
        accept(); // Close dialog on success
    }
    else {
        QMessageBox::warning(this, "错误", "通知发送失败");
    }
}

// Handle notification type change
void SendNotificationDialog::on_TypeComboBox_currentIndexChanged(int index)
{
    if (index == 0) { // System announcement
        ui->ReceiverEdit->setVisible(false);
        ui->notificationTitleEdit->setEnabled(true);
        ui->label_2->setEnabled(true);
    }
    else { // Personal notification
        ui->ReceiverEdit->setVisible(true);
        ui->notificationTitleEdit->setEnabled(false);
        ui->label_2->setEnabled(false);
    }
}

// Send system announcement to all users
bool SendNotificationDialog::sendSystemAnnouncement(const QString& title, const QString& content)
{
    // Use the C function to broadcast announcement
    bool result = admin_send_announcement(
        m_senderUsername.toStdString().c_str(),
        title.toStdString().c_str(),
        content.toStdString().c_str()
        );

    return result;
}

// Send personal notification to specific user
bool SendNotificationDialog::sendPersonalNotification(const QString& receiver, const QString& content)
{
    // Initialize users list from file for user verification
    init_users_for_notification("users.txt");

    // Use the C function to send a notification
    QString type = "announcement"; // Default to announcement type
    bool result = send_notification(
        receiver.toStdString().c_str(),
        m_senderUsername.toStdString().c_str(),
        type.toStdString().c_str(),
        content.toStdString().c_str()
        );

    // Clean up
    cleanup_notification_system();

    return result;
}

// Get all usernames from users.txt
QStringList SendNotificationDialog::getAllUsernames()
{
    QStringList usernames;

    // Load users using the C function
    struct users* usersList = loadUsersFromFile("users.txt");
    if (!usersList) {
        qDebug() << "Failed to load users";
        return usernames;
    }

    // Iterate through the linked list and add usernames
    struct users* current = usersList;
    while (current != nullptr) {
        usernames.append(QString(current->username));
        current = current->next;
    }

    // Free the linked list
    freeUsers(usersList);

    return usernames;
}

// Map internal notification type to display type
QString SendNotificationDialog::getNotificationType()
{
    switch (ui->TypeComboBox->currentIndex()) {
    case 0:
        return "announcement"; // System announcement
    case 1:
        return "personal"; // Personal notification
    default:
        return "announcement";
    }
}

// Check if username exists in the system
bool SendNotificationDialog::isValidUsername(const QString& username)
{
    // Initialize users list from file
    init_users_for_notification("users.txt");

    // Find user by username
    struct users* user = find_user_by_username(username.toStdString().c_str());

    // Clean up
    bool exists = (user != nullptr);
    cleanup_notification_system();

    return exists;
}
